package com.verykim.video;

import com.google.appengine.api.datastore.AsyncDatastoreService;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;

public final class Category {

	final static String P_NAME = "name";
	final static String P_PARENT = "parent";

	private String name;
	private Long parent;

	public void Name(final String name) {
		this.name = name;
	}

	public void Parent(final int parent) {
		this.parent = (long) (Integer.MAX_VALUE + parent);
	}

	public static boolean add(final Category category) throws Exception {
		final DatastoreService ds = DatastoreServiceFactory
				.getDatastoreService();
		final Entity E = new Entity(Category.class.getSimpleName(),
				category.name);
		E.setProperty(P_PARENT, category.parent);
		return ds.put(E).isComplete();
	}

	public static boolean delete(final String name) throws Exception {
		final AsyncDatastoreService ads = DatastoreServiceFactory
				.getAsyncDatastoreService();
		final String kind = Category.class.getSimpleName();
		try {
			final Key k = KeyFactory.createKey(null, kind, name);
			ads.delete(k);
		} catch (Exception e) {
			return false;
		} finally {

		}
		return true;
	}

	public static Iterable<Entity> categorys() {
		final DatastoreService ds = DatastoreServiceFactory
				.getDatastoreService();
		final Query q = new Query(Category.class.getSimpleName());
		q.addSort(P_PARENT, SortDirection.ASCENDING);
		final PreparedQuery pq = ds.prepare(q);
		return pq.asList(FetchOptions.Builder.withDefaults());
	}
}
